<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>简易画板</title>
</head>

<body>
    <canvas id="canvas" width="600" height="300" style="background-color: black;"></canvas><br />

    画笔的颜色：<input type="color" id="color" value="#ffffff" /><br />
    背景的颜色：<input type="color" id="background" /><br />
    线的粗细：<input type="number" id="size" value="4" step="1" /><br />
    <button id="btn">保存为图片</button>
</body>

</html>
<script>
    //初始化全局变量
    var size = 4; //线的粗细
    var background = 'black' //背景颜色
    var color = 'white' //线的颜色
    var startX = startY = 0 //起始点的坐标
    var isDraw = false //false 说明没在绘画 true绘画中

    //定义生成画布
    var canvas = document.getElementById("canvas");
    //创建2D工作台
    var ctx = canvas.getContext("2d");

    //给画布做绘画效果
    //绑定事件（鼠标点击、弹起、移动）
    canvas.addEventListener("mousedown", down)
    canvas.addEventListener("mouseup", up)
    canvas.addEventListener("mousemove", move)

    //鼠标按下
    function down(e) {
        //定义起始点
        startX = e.pageX - 10
        startY = e.pageY - 10

        //修改绘画状态
        isDraw = true
    }

    //鼠标弹起
    function up(e) {
        isDraw = false
    }

    //鼠标移动
    function move(e) {
        //判断当前是否处于绘画状态
        if (isDraw) {
            //获取移动的坐标
            var endX = e.pageX - 10
            var endY = e.pageY - 10

            //开始划线
            ctx.beginPath()
            //设置画笔颜色
            ctx.strokeStyle = color
            //设置画笔的粗细
            ctx.lineWidth = size
            //设置画笔的线头
            ctx.lineCap = 'round'

            //标记起始点坐标
            ctx.moveTo(startX, startY)
            ctx.lineTo(endX, endY)

            //最后描绘出来
            ctx.stroke()
            ctx.closePath()

            //画完之后，要将本次的结束点作为下一次的起始点
            startX = endX
            startY = endY
        }
    }

    //给元素绑定事件(样式修改)
    var colorDom = document.getElementById('color')
    var backgroundDom = document.getElementById('background')
    var sizeDom = document.getElementById('size')
    var btn = document.getElementById('btn')

    colorDom.addEventListener('change', function () {
        color = this.value
    })

    backgroundDom.addEventListener('change', function () {
        background = this.value
        canvas.style.background = background
    })

    sizeDom.addEventListener('change', function () {
        var num = parseInt(this.value)
        if (num <= 4) {
            num = 4
        }

        size = num
    })

    //保存成图片（画布默认背景为透明，需创建新的画布，作为背景，置于底层）
    btn.addEventListener("click", function () {
        //创建一个新的画布
        var downloadCanvas = document.createElement("canvas")
        //构建2D工作台
        var downloadCtx = downloadCanvas.getContext("2d")

        //统一画布大小
        downloadCanvas.width = canvas.width
        downloadCanvas.height = canvas.height

        //设置背景层和内容层的层级关系
        downloadCtx.globalCompositeOperation = 'destination-over'

        //获取原画布的内容，将内容铺到背景层上面
        var data = ctx.getImageData(0, 0, canvas.width, canvas.height)
        downloadCtx.putImageData(data, 0, 0)

        //给新画布设置背景颜色
        downloadCtx.fillStyle = background
        downloadCtx.fillRect(0, 0, downloadCanvas.width, downloadCanvas.height)

        //将画布下载成图片

        //先将画布生成一个下载链接
        var url = downloadCanvas.toDataURL()

        //创建a元素
        var a = document.createElement('a')
        a.href = url
        a.download = 'download.png'
        //触发模拟点击
        a.click()
        //最后下载下来了那么download和a都没有用了就销毁
        downloadCanvas.remove()
        a.remove()
    })
</script>